package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.example.config.JwtTokenUtil;
import org.example.domain.Identity;
import org.example.domain.Role;
import org.example.domain.bean.LoginRequest;
import org.example.domain.bean.RestResponse;
import org.example.mapper.IdentityMapper;
import org.example.service.IIdentityService;
import org.example.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author blackTry
 * @since 2021-04-11
 */
@Service
public class IdentityServiceImpl extends ServiceImpl<IdentityMapper, Identity> implements IIdentityService {

    @Resource
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

//    @Autowired
//    private AliOssService aliOssService;

    @Autowired
    private IRoleService roleService;


    /**
     * 登陆之后返回token
     * @param loginRequest
     * @param request
     * @return
     */
    @Override
    public RestResponse<Map<String,String>> login(LoginRequest loginRequest, HttpServletRequest request) {
        String captcha = (String)request.getSession().getAttribute("captcha");
        if(StrUtil.isBlank(loginRequest.getVerifyCode()) || !captcha.equalsIgnoreCase(loginRequest.getVerifyCode())){
            return RestResponse.fail(-1,"验证码输入错误,请重新输入!");
        }
        // 登录用户判断
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequest.getUsername());
        if(null==userDetails || !passwordEncoder.matches(loginRequest.getPassword(),userDetails.getPassword())){
            return RestResponse.fail(-1,"用户名或者密码错误!");
        }
        if(!userDetails.isEnabled()){
            return RestResponse.fail(-1,"账号被禁用，请联系管理员!");
        }
        // 更新登录对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken) ;
        // 生成对应token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RestResponse.success(tokenMap);
    }

    @Override
    public Identity getIdentityByUserName(String username) {
        QueryWrapper<Identity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Identity::getNoId,username).eq(Identity::getEnable,true);
        Identity identity = this.baseMapper.selectOne(wrapper);
        return identity;
    }

    @Override
    public List<Role> getRoles(Long identityId) {
        return roleService.getRoles(identityId);
    }

}
